<?php

namespace app\admin\controller\store;

use app\admin\model\purcha\Data;
use app\admin\model\house\In;
use app\admin\model\Warehouse;
use app\common\controller\Backend;
use think\Db;
use think\Session;
use think\Url;

/**
 * 采购订单
 *
 * @icon fa fa-circle-o
 */
class Purcha extends Backend
{

    /**
     * Purcha模型对象
     * @var \app\admin\model\Purcha
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Purcha;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function view($ids){

        $pData = new Data();
        $list = $pData->where(array('pur_id'=>$ids))->select();
        $this->assign('list',$list);

        $this->assign('info',$this->model->find($ids));
        //入库记录
        $wDb = new In();
        $wlist = Db::name('house_in')->where(array('pur_id'=>$ids,'type'=>1))->order('id desc')->paginate(10,false,[
            'query'=>request()->param()
            ,
        ]);
        $this->assign("wlist",$wlist);
        //入库记录
        /* $wDb2 = new Retreat();
         $wlist2 = collection($wDb2->where(array('pid'=>$ids))->order('id desc')->select())->toArray();*/
        //$this->assign("wlist2",$wlist2);
        return $this->view->fetch();
    }

    /*
     * 采购入库
     * */
    public function ruku(){
        if ($this->request->isPost() && $this->request->isAjax()) {
            $params = $this->request->post();
            $pur_id = $params['pur_id'];
            $str = $params['str'];//post商品参数
            $arr = array_filter(explode(',',$str));//逗号分隔，商品id，数量
            if (!$arr)$this->error("没有任何数据入库");
            /*
             * 1.修改采购单状态表
             * 2.多增加入库记录数据  hdyj_house_in 商品id,商品数量，仓库ID，仓库id默认为1，总仓库  所操作id,type=1为采购订单id
             * 3.修改采购数据表入库数量 多条数据
             * 4.入仓库，根据商品id,仓库id，累修改
             *
            */
            $cid = 1;//总部仓库
            $houseDb = new In();//仓库表
            $order_id = $houseDb->getOrderId();
            $pur_data_db = new Data();//采购单数据表
            $stockDb = new \app\admin\model\Stock();//库存表
            $admin = Session::get('admin');

            $publisher=$admin['userid'];
            foreach ($arr as $k=>$v){
                list($shopid,$num) = explode("|",$v);
                if ($num==0)break;
                $houseArr=array(
                    'order_id'=>$order_id,
                    'type'=>1,
                    'shopid'=>$shopid,
                    'num'=>$num,
                    'cid'=>$cid,
                    'pur_id'=>$pur_id,
                    'inputtime'=>time(),
                    'publisher'=>$publisher
                );
                $houseDb->insert($houseArr);
                $pur_data_db->where(array('pur_id'=>$pur_id,"shopid"=>$shopid))->setInc('actual', $num);
                //如果已经存在数据，在库存基础上添加
                if ($stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->find()){
                    $stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->setInc('num', $num);
                }else{
                    Db::name('stock')->insert(array('cid'=>$cid,'num'=>$num,'shopid'=>$shopid));
                }

            }
            $this->model->where(array('id'=>$pur_id))->update(array('status'=>1));
            $this->success("操作成功");
            /*修改状态*/
        }

    }
    public function ware($id){
        $pData = new Data();
        $pinfo = $pData->find($id)->toArray();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //验证数量
                if ($params['num'] < 1 || $params['num'] > ($pinfo['num']-$pinfo['actual'])){
                    $this->error("数量不能大于".($pinfo['num']-$pinfo['actual']));
                }


                Db::startTrans();
                try{
                    $wDb = new Warehouse();
                    $params['wid']=$this->orderId($wDb,'IN');
                    $params['createtime']=time();
                    $admin = Session::get('admin');

                    $params['publisher']=$admin['userid'];
                    $params['did']=$id;
                    $params['pid']=$pinfo['pur_id'];
                    $wDb->insert($params);
                    //入库单完成

                    $pData->where(array('did'=>$id))->setInc('actual', $params['num']);
                    //操作采购单附表数据进入记录
                    //修改库存
                    $preDb = new \app\admin\model\Preproduct();
                    $preDb->where(array('id'=>$pinfo['shopid']['id']))->setInc('storenum', $params['num']);


                    //操作采购单数量相加
                    $cg = $this->model->find($pinfo['pur_id']);
                    if ($cg['actual']==0)db('purcha')->where('id',$pinfo['pur_id'])->update(['status' => '2']);



                    //数量刚好匹配
                    if ($cg['actual']+$params['num']==$cg['total'])db('purcha')->where('id',$pinfo['pur_id'])->update(['status' => '1']);
                    $this->model->where('id',$pinfo['pur_id'])->setInc('actual', $params['num']);


                    // 提交事务
                    Db::commit();

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success("1<script type='text/javascript'>location.reload();</script>");



            }else {
                $this->error(__('Parameter %s can not be empty', ''));
            }

        }
        $this->assign('info',$pinfo);
        return $this->view->fetch();
    }

    protected function orderId($wDb,$type){
        $order_id = $type."- " . date('Ymd') . '- ' . random(6, 1);
        $info = $wDb->where(array('wid' => $order_id))->find();

        if ($info) {
            $this->orderId($wDb,$type);
        } else {
            return $order_id;
        }


    }

    public function voids($ids){
        $ids = intval($ids);
        if ($this->request->isPost()) {
            //查看订单状态
            $info = $this->model->find($ids);
            if (!$info)$this->error("订单不存在");
            if (!$info['status']==4)$this->error("此订单已作废");
            $pDataDb = new \app\admin\model\Purcha\Data();
            $list=Db::name("purcha_data")->field('shopid,actual')->where(array('pur_id'=>$ids))->select();
            $sDb = new \app\admin\model\Stock();
            foreach ($list as $v){
                //先检测总部库存
                $stinfo = $sDb->where(array("cid"=>1,'shopid'=>$v['shopid']))->find();
                if ($stinfo['num'] < $v['actual'])$this->error("库存不足");
            }
            $outDb = new \app\admin\model\Houseout();
            $order_id = $outDb->getOrderId();
            $admin = Session::get('admin');

            $publisher=$admin['userid'];

            foreach ($list as $v){
                $outDb->insert(array(
                    "order_id"=>$order_id,
                    'type'=>7,
                    'shopid'=>$v['shopid'],
                    'num'=>$v['actual'],
                    'cid'=>1,
                    'pur_id'=>$info['order_id'],
                    'inputtime'=>time(),
                    'publisher'=>$publisher,
                    'mark'=>"作废订单-".$info['order_id'],
                    "bcp"=>''

                ));
                $sDb->where(array("cid"=>1,'shopid'=>$v['shopid']))->setDec("num",$v['actual']);
            }
            $this->model->where(array('id'=>$ids))->update(array('status'=>4));
            $this->success();

        }
    }
    public function import(){
        ini_set('memory_limit','3072M');    // 临时设置最大内存占用为3G
        set_time_limit(0);   //
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS .$file;

        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);


        //获取生产商id
        $supplier = $currentSheet->getCellByColumnAndRow(9,4)->getValue();
        $supDb = new \app\admin\model\Supplier();
        //查询供应商是否存在
        $supInfo = $supDb->where(array("sname"=>trim($supplier)))->find();
        if (!$supInfo)$this->error("请添加供应商");
        $sdate =str_replace(array("年","月","日"),array("-","-",""), mb_substr($currentSheet->getCellByColumnAndRow(0,3)->getValue(),6));//2019年09月11日
        $preDb = new \app\admin\model\Preproduct();
        $lists = array();
        $total=0;
        $totals=0;
        for ($currentRow = 9; $currentRow <= $allRow; $currentRow++) {

            $cname = $currentSheet->getCellByColumnAndRow(1,$currentRow)->getValue();//产品名称
            if (!empty($cname)){
                $num = trim($currentSheet->getCellByColumnAndRow(11,$currentRow)->getValue());//数量
                $nums = trim($currentSheet->getCellByColumnAndRow(13,$currentRow)->getValue());//数量

                $yinzhang = trim($currentSheet->getCellByColumnAndRow(5,$currentRow)->getValue());//数量
                $info = $preDb->where(array("cname"=>$cname,"type"=>1))->find();

                if(!$info)$this->error($cname."不存在,在第 ".$currentRow." 行");
                if ($num <=0)$this->error($cname."数量为0");
                $lists[]=array("actual"=>$nums,"price"=>trim($currentSheet->getCellByColumnAndRow(8,$currentRow)->getValue()),"id"=>$info['id'],"num"=>$num,'yinzhang'=>$yinzhang ? $yinzhang  : 0);
                $total+=$num;
                $totals+=$nums;

            }else{
                //退出循环
                break;
            }
        }
        $admin = Session::get('admin');

        $publisher=$admin['userid'];
        if (!$lists)$this->error("没有导入商品");

        $purArr = array(
            "supplier"=>$supInfo['id'],
            "createtime"=>strtotime($sdate),
            "publisher"=>$publisher,
            "mark"=>"生产单入库",
            "order_id"=>$this->model->getOrderId(),
            "status"=>$totals==$total ? 1 : 2,
            "total"=>$total,
            "actual"=>$total


        );

        $this->model->save($purArr);
        $inId = $this->model->getLastInsID();

        foreach ($lists as $v){
            Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],"yinzhang"=>$v['yinzhang'],'price'=>$v['price'],"actual"=>$v['actual'],'pur_id'=>$inId));
            //Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>$v['price'],'pur_id'=>$result));

        }

        $pur_id = $inId;
        /*
         * 1.修改采购单状态表
         * 2.多增加入库记录数据  hdyj_house_in 商品id,商品数量，仓库ID，仓库id默认为1，总仓库  所操作id,type=1为采购订单id
         * 3.修改采购数据表入库数量 多条数据
         * 4.入仓库，根据商品id,仓库id，累修改
         *
        */
        $pur_data_db = new Data();//采购单数据表

        $cid = 1;//总部仓库
        $houseDb = new In();//仓库表
        $order_id = $houseDb->getOrderId();
        $stockDb = new \app\admin\model\Stock();//库存表
        $admin = Session::get('admin');
        foreach ($lists as $k=>$v){
            $shopid=$v['id'];
            $num=$v['actual'];
            $houseArr=array(
                'order_id'=>$order_id,
                'type'=>1,
                'shopid'=>$shopid,
                'num'=>$num,
                'cid'=>$cid,
                'pur_id'=>$pur_id,
                'inputtime'=>strtotime($sdate),
                'publisher'=>$publisher
            );
            $houseDb->insert($houseArr);
            //如果已经存在数据，在库存基础上添加
            if ($stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->find()){
                $stockDb->where(array('cid'=>$cid,"shopid"=>$shopid))->setInc('num', $num);
            }else{
                Db::name('stock')->insert(array('cid'=>$cid,'num'=>$num,'shopid'=>$shopid));
            }

        }

        $this->success();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $post = $this->request->post();
                    if (!isset($post['shop']) && !$post['shop'])$this->error("必须选择商品");
                    $params['total']=array_sum(array_column($post['shop'],'num'));
                    $result = $this->model->allowField(true)->save($params);
                    $inId = $this->model->getLastInsID();

                    foreach ($post['shop'] as $v){
                        Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>$v['price'],'pur_id'=>$inId));
                        //Db::name('purcha_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>$v['price'],'pur_id'=>$result));

                    }
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


}